package com.xscha.tableforge.controller;

import com.xscha.tableforge.model.dto.TableDataDto;
import com.xscha.tableforge.model.dto.TableDataQueryDto;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import com.xscha.soyue.common.core.domain.R;
import com.xscha.tableforge.service.TableDataService;
import com.xscha.tableforge.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/data")
public class TableDataController {
    private final TableDataService dynamicTableService;
    @Autowired
    public TableDataController(TableDataService dynamicTableService) {
        this.dynamicTableService = dynamicTableService;
    }

    @GetMapping("/table/{tableId}")
    public R<List<Map<String, Object>>> queryData(
            @PathVariable String tableId,
            @RequestParam(required = false) Map<String, Object> conditions) {
        try {
            List<Map<String, Object>> data = dynamicTableService.queryData(tableId, conditions);
            return R.ok(data);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
    
    @PostMapping("/table/{tableId}/page")
    public R<PageResult<Map<String, Object>>> queryDataPage(
            @PathVariable String tableId,
            @RequestBody TableDataQueryDto queryDto) {
        try {
            PageReq pageRequest = new PageReq();
            pageRequest.setPageNum(queryDto.getPageNum());
            pageRequest.setPageSize(queryDto.getPageSize());
            pageRequest.setOrderBy(queryDto.getOrderBy());
            pageRequest.setOrderDirection(queryDto.getOrderDirection());
            
            PageResult<Map<String, Object>> data = dynamicTableService.queryDataPage(
                    tableId, queryDto.getConditions(), pageRequest);
            return R.ok(data);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("/table/{tableId}")
    public R<Map<String, Object>> insertData(
            @PathVariable String tableId,
            @RequestBody TableDataDto dataDto) {
        try {
            Map<String, Object> insertedData = dynamicTableService.insertData(tableId, dataDto.getData(), SecurityUtils.getUserId());
            return R.ok(insertedData);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("/table/{tableId}/records")
    public R<Map<String, Object>> saveRecord(
            @PathVariable String tableId,
            @RequestBody TableDataDto dataDto) {
        try {
            Map<String, Object> insertedData = dynamicTableService.saveRecord(tableId, dataDto.getData(), SecurityUtils.getUserId());
            return R.ok(insertedData);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @PutMapping("/table/{tableId}/{recordId}")
    public R<Map<String, Object>> updateData(
            @PathVariable String tableId,
            @PathVariable String recordId,
            @RequestBody TableDataDto dataDto) {
        try {
            Map<String, Object> updatedData = dynamicTableService.updateData(tableId, recordId, dataDto.getData(), SecurityUtils.getUserId());
            return R.ok(updatedData);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @DeleteMapping("/table/{tableId}/{recordId}")
    public R<Void> deleteData(
            @PathVariable String tableId,
            @PathVariable String recordId) {
        try {
            dynamicTableService.softDeleteData(tableId, recordId, SecurityUtils.getUserId());
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询记录及其关联数据
     */
    @GetMapping("/table/{tableId}/record/{recordId}/with-relations")
    public R<Map<String, Object>> queryRecordWithRelations(
            @PathVariable String tableId,
            @PathVariable String recordId,
            @RequestParam(required = false) List<String> includeRelations) {
        try {
            Map<String, Object> data = dynamicTableService.queryRecordWithRelations(
                    tableId, recordId, includeRelations);
            return R.ok(data);
        } catch (Exception e) {
            e.printStackTrace(); // 添加异常堆栈打印，方便调试
            return R.fail(e.getMessage());
        }
    }
}